package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.bean.acttimelimit;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.lockorder.LockOrderInfo;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ActiveModule_每日特惠 extends PlayerModule {

	//bean ----------------------------------------------------
	public static final int acttype = 117;
	
	private int group;	//从小到大循环
	private DateTime update;	//group更新时间
	private HashMap<Integer, Integer> idmap = new HashMap<Integer, Integer>();	//key:id value:goodsid
	private ArrayList<Integer> buygoodsids = new ArrayList<Integer>();	//购买的商品id 
	private HashMap<Integer, DateTime> lockordermap = new HashMap<Integer, DateTime>();		//锁单 key：goodsid value:time
	
	public int getGroup() {
		return group;
	}
	public void setGroup(int group) {
		this.group = group;
	}
	public DateTime getUpdate() {
		return update;
	}
	public void setUpdate(DateTime update) {
		this.update = update;
	}
	public HashMap<Integer, Integer> getIdmap() {
		return idmap;
	}
	public void setIdmap(HashMap<Integer, Integer> idmap) {
		this.idmap = idmap;
	}
	public ArrayList<Integer> getBuygoodsids() {
		return buygoodsids;
	}
	public void setBuygoodsids(ArrayList<Integer> buygoodsids) {
		this.buygoodsids = buygoodsids;
	}
	public HashMap<Integer, DateTime> getLockordermap() {
		return lockordermap;
	}
	public void setLockordermap(HashMap<Integer, DateTime> lockordermap) {
		this.lockordermap = lockordermap;
	}
	
	//func ----------------------------------------------------

	/**
	 * 能否购买
	 * @param goodsid
	 * @return
	 */
	public int canbuy(int goodsid) {
		if(getBuygoodsids().contains(goodsid)) {
			return DrawStatus.hadget.getStatus();
		}
		
		if(getLockordermap().containsKey(goodsid)) {
			return DrawStatus.cannotget.getStatus();
		}
		
		return DrawStatus.canget.getStatus();
	}

//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;
	
	/** 创建ActiveModule_每日特惠
	 * @param pcode
	 */
	public static ActiveModule_每日特惠 create(String pcode) {
		PlayerBean pb = PlayerBean.get(pcode);
		int sid = pb.getServerId();

		ServerBean sb = ServerBean.get(sid);
		int areaid = sb.getAreaId();
		
		activeControl sai = activeControl.get(areaid, acttype);
		if(sai == null) {
			return null;
		}
		
		if(!sai.isRuning()) {
			return null;
		}
		
		int day = 0;
		Map<String, acttimelimit> execlmap = ActDataCenter.getAllData(acttimelimit.class, pcode);
		for(acttimelimit execl : execlmap.values()) {
			if(day == 0) {
				day = execl.getDay();
			}else {
				day = Math.min(day, execl.getDay());
			}
		}
		
		if(day <= 0) {
			return null;
		}
		
		ActiveModule_每日特惠 am = new ActiveModule_每日特惠();
		am.setTimeline(sai.getTimeline());
		am.setPlayerCode(pcode);
		am.setUpdate(DateTime.now());
		am.setGroup(day);
		
		for(acttimelimit execl : execlmap.values()) {
			if(execl.getDay() == day) {
				am.getIdmap().put(execl.getId(), execl.getChargeid());
			}
		}
		
		am.set();
		return am;
	}

	public void update() {
//		PlayerBean pb = PlayerBean.get(getPlayerCode());
//		int sid = pb.getServerId();
//		ServerBean sb = ServerBean.get(sid);
//		int areaid = sb.getAreaId();

		AreaBean ab = AreaModule.area(getPlayerCode());
		activeControl sai = activeControl.get(ab.getAreaId(), acttype);
		if (sai == null) {
			return;
		}

		// 关闭活动
		if (!sai.running() && running()) {
			setTimeline(sai.getTimeline());
			set();
		}

		// 开启活动
		if (sai.running() && !running()) {

			int day = 0;
			Map<String, acttimelimit> execlmap = ActDataCenter.getAllData(acttimelimit.class, getPlayerCode());
			for(acttimelimit execl : execlmap.values()) {
				if(day == 0) {
					day = execl.getDay();
				}else {
					day = Math.min(day, execl.getDay());
				}
			}
			
			if(day <= 0) {
				return;
			}
			
			setTimeline(sai.getTimeline());
			setPlayerCode(getPlayerCode());
			setUpdate(DateTime.now());
			setGroup(day);
			
			for(acttimelimit execl : execlmap.values()) {
				if(execl.getDay() == day) {
					getIdmap().put(execl.getId(), execl.getChargeid());
				}
			}
			
			set();
			
		}

		// 刷新锁单时间
		HashMap<Integer, DateTime> map = getLockordermap();
		if (map.size() != 0) {
			ArrayList<Integer> goodsids = new ArrayList<Integer>();
			for (int goodsid : map.keySet()) {
				DateTime locktime = map.get(goodsid);

				if (DateTime.now().getMillis() - locktime.getMillis() > LockOrderInfo.lockTime()) {
					goodsids.add(goodsid);
				}
			}

			boolean save = false;
			for (int goodsid : goodsids) {
				getLockordermap().remove(goodsid);
				save = true;
			}

			if (save) {
				set();
			}
		}
		
		//刷新活动信息
		int days = ActiveUtil.days(getUpdate(), DateTime.now());
		if(days >= 1) {
			int newgroup = getGroup() + days;
			
			Map<String, acttimelimit> execlmap = ActDataCenter.getAllData(acttimelimit.class, getPlayerCode());
			ArrayList<Integer> groups = new ArrayList<Integer>();
			for(acttimelimit execl : execlmap.values()) {
				if(!groups.contains(execl.getDay())) {
					groups.add(execl.getDay());
				}
			}
			
			if(!groups.contains(newgroup)) {
				newgroup = 1;
				for (int g : groups) {
					newgroup = Math.min(newgroup, g);
				}
			}
			
			setBuygoodsids(new ArrayList<Integer>());
			setGroup(newgroup);
			setLockordermap(new HashMap<Integer, DateTime>());
			setIdmap(new HashMap<Integer, Integer>());
			setUpdate(DateTime.now());
			
			for(acttimelimit execl : execlmap.values()) {
				if(newgroup == execl.getDay()) {
					getIdmap().put(execl.getId(), execl.getChargeid());
				}
			}
			
			set();
		}
	}

	/**
	 * 处理购买
	 * @param goodsid
	 */
	public void dealbuy(int goodsid) {
		getBuygoodsids().add(goodsid);
		getLockordermap().remove(goodsid);
		set();
	}
	
	//锁单
	public void lockorder(int goodsid) {
		getLockordermap().put(goodsid, DateTime.now());
		set();
	}
	
	//解锁
	public void unlockorder(int goodsid) {
		getLockordermap().remove(goodsid, DateTime.now());
		set();
	}
	
	// redis ---------------------------------------------------------

	static private String key(String playerCode) {
		return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
	}

	public void set() {
		try {
			setv(key(getPlayerCode()), this);
			check();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取 ActiveModule_每日特惠
	 * 
	 * @param playerCode
	 * @return
	 */
	static public ActiveModule_每日特惠 get(String playerCode, Boolean isNewPlayer) {
		try {
			ActiveModule_每日特惠 module = getv(key(playerCode));
			if (module == null) {

				//新用户不需要去查数据库
				if(!isNewPlayer){
					module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_每日特惠.class);
					if(module != null){module.set();}//同步到redis
				}

				if (module == null) {
					module = create(playerCode);
				}
				if(module == null){return null;}
			}
			
			module.update();
			module.check();

			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/** 查看是否有可领取奖励 控制红点 */
	public void check() {
		if(running()) {
			ArrayList<Integer> goodids = new ArrayList<Integer>();
			for(int goodis : getBuygoodsids()) {
				if(getBuygoodsids().contains(goodids)) {
					continue;
				}
				goodids.add(goodis);
			}
			
			if(goodids.size() == getIdmap().size()) {
				new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.领完了);
			}else {
				new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
			}
		}else {
			new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
		}
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				ActiveModule_每日特惠 activeModule_每日特惠 = getv(key(playerCode));
				if (activeModule_每日特惠 != null) MySQLCacheDAO.setV(key, activeModule_每日特惠);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}

}
